package com.qdairlines.cas;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasAuthenticationException;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.cas.CasToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.util.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Autowired;

import com.qdairlines.entity.user.User;
import com.qdairlines.service.user.PermissionService;
import com.qdairlines.service.user.RoleService;
import com.qdairlines.service.user.UserService;



public class MyCasRealm extends CasRealm{
   
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @SuppressWarnings("rawtypes")
	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principals;
		List listPrincipals = principalCollection.asList();
		Map attributes = (Map) listPrincipals.get(1);
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		String workcode = (String) attributes.get("employeeID");

		User user = userService.getUserByWorkcode(workcode);
		if (null != user) {
			// 为当前用户设置角色和权限
			List<String> userRoleNameList = roleService.listRoleCodeByWorkcode(user.getWorkcode());
			List<String> userPermissionNameList =  permissionService.listPermissionCodeByWorkcode(user.getWorkcode());
			simpleAuthorizationInfo.setRoles(new HashSet<String>(userRoleNameList));
			simpleAuthorizationInfo.setStringPermissions(new HashSet<String>(userPermissionNameList));
		} else {
			throw new AuthorizationException();
		}
		return simpleAuthorizationInfo;
    	
        
        
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    	CasToken casToken = (CasToken) token;
		if (casToken == null)
			return null;

		//
		String userName=(String)casToken.getPrincipal();
		if(userName!=null &&userName.length()>1){
			User user=userService.getUserByUserName((userName));
			this.setSession("currentUser", user);
			String ticket="";
			Map attributes=new HashMap();
			attributes.put("employeeID", user.getWorkcode());
			attributes.put("displayName", user.getUserName());
			List principals = CollectionUtils.asList(new Object[] { userName,
					attributes });
			PrincipalCollection principalCollection = new SimplePrincipalCollection(
					principals, getName());

	        //this.setSession(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.CHINESE);
			return new SimpleAuthenticationInfo(principalCollection, ticket);
		}
		else
		{
			// 正常套路验证
			String ticket = (String) casToken.getCredentials();
			if (!StringUtils.hasText(ticket))
				return null;
			TicketValidator ticketValidator = ensureTicketValidator();
			
			
			try {
				Assertion casAssertion = ticketValidator.validate(ticket,
						getCasService());
				AttributePrincipal casPrincipal = casAssertion.getPrincipal();
				String userId = casPrincipal.getName();
				Map attributes = casPrincipal.getAttributes();
				String name = (String) attributes.get("displayName");
				String employeeId = (String) attributes.get("employeeID");
				String department = (String) attributes.get("department");
				// 对获取到的信息进行再处理
				casToken.setUserId(userId);
				List principals = CollectionUtils.asList(new Object[] { userId,
						attributes });

				User user = userService.getUserByWorkcode((employeeId));
				//User user1 = userService.getUserByUserName(user.getUserName());
				this.setSession("currentUser", user);
				//this.setSession(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.CHINESE);
				PrincipalCollection principalCollection = new SimplePrincipalCollection(
						principals, getName());
				return new SimpleAuthenticationInfo(principalCollection, ticket);
			} catch (TicketValidationException e) {
				throw new CasAuthenticationException((new StringBuilder())
						.append("Unable to validate ticket [").append(ticket)
						.append("]").toString(), e);
			}
		}
    }
    
    private void setSession(Object key, Object value) {
	Subject currentUser = SecurityUtils.getSubject();
	if (null != currentUser) {
	    Session session = currentUser.getSession();
	    if (null != session) {
		session.setAttribute(key, value);
	    }
	}
    }
    
}
